package com.gyf.base.data.net

import android.util.Log
import com.gyf.base.common.BaseConstant
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitFactory private constructor() {
    companion object {
        val instance: RetrofitFactory by lazy { RetrofitFactory() }
    }

    private val retrofit: Retrofit
    private val interceptor: Interceptor

    init {
        interceptor = Interceptor { chain ->
            val request = chain.request()
                    .newBuilder()
                    .header("Content-Type", "application/json")
                    .addHeader("charset", "uft-8")
                    .build();
            chain.proceed(request);
        }

        retrofit = Retrofit.Builder()
                .baseUrl(BaseConstant.server_address)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(initClient())
                .build();
    }

    private fun initClient(): OkHttpClient? {
        return OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .addInterceptor(initLoginterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private fun initLoginterceptor(): Interceptor? {
        val httpLoggingInterceptor = HttpLoggingInterceptor() {
            Log.d("gyf", it);
        };
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY;
        return httpLoggingInterceptor;
    }

    fun <T> create(service: Class<T>): T {
        return retrofit.create(service);
    }
}